package com.xzy.rabbit.demo.deadqueue.b;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 死信队列_队列已满
 *
 * @author xzy
 * @date 2021/9/2811:20
 */
@Slf4j
@AllArgsConstructor
class ConsumerDead implements Runnable {
    /**
     * 非持久化队列（RabbitMQ重启后队列消失）
     */
    private static final boolean DURABLE = false;
    /**
     * 独占队列（当前Connection独占）
     */
    private static final boolean EXCLUSIVE = false;
    /**
     * 自动删除队列（不再使用时自动删除）
     */
    private static final boolean AUTO_DELETE = false;

    private final Connection connection;
    private final String deadExchangeName;
    private final String deadRoutingKey;
    private final String deadQueueName;

    public void consume() throws IOException {
        // 1.获取信道
        Channel channel = connection.createChannel();

        // 2.声明队列
        channel.queueDeclare(deadQueueName, DURABLE, EXCLUSIVE, AUTO_DELETE, null);

        // 3.绑定交换机（多重绑定）
        channel.queueBind(deadQueueName, deadExchangeName, deadRoutingKey);

        // 4.接收消息
        String currentThread = Thread.currentThread().getName();
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            log.info(currentThread + " 成功接收：`{}`<----{}\n", new String(message.getBody()), deadRoutingKey);
        };
        CancelCallback cancelCallback = consumerTag -> {
            log.info(currentThread + " 取消接收\nconsumeTag ==> {}\n", consumerTag);
        };
        channel.basicConsume(deadQueueName, true, deliverCallback, cancelCallback);
    }

    @Override
    public void run() {
        try {
            consume();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
